package com.xinsilu.hospital.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinsilu.hospital.entity.AuthsysMenu;
import com.xinsilu.hospital.entity.AuthsysMenuMeta;
import com.xinsilu.hospital.mapper.AuthsysMenuMapper;

import com.xinsilu.hospital.mapper.AuthsysMenuMetaMapper;
import com.xinsilu.hospital.service.IAuthsysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ym
 * @since 2021-11-30
 */
@Service
public class AuthsysMenuServiceImpl extends ServiceImpl<AuthsysMenuMapper, AuthsysMenu> implements IAuthsysMenuService {

    @Autowired
    private AuthsysMenuMapper menuMapper;
    @Autowired
    private AuthsysMenuMetaMapper metaMapper;
    @Override
    public List<AuthsysMenu> findFirstMenus() {
        return this.menuMapper.selectAll();
    }

    @Override
    public AuthsysMenu findById(int mnId) {
        return this.menuMapper.selectByPrimaryKey(mnId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void addMenu(AuthsysMenu menu) {
        // 添加一级menu
        this.menuMapper.insert(menu);
        AuthsysMenuMeta meta = menu.getMeta();
        if(meta != null){
            meta.setMnId(menu.getId());
            this.metaMapper.insert(meta);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void editMenu(AuthsysMenu menu) {
        this.menuMapper.updateByPrimaryKey(menu);
        if(menu.getMeta() != null){
            this.metaMapper.updateByPrimaryKey(menu.getMeta());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteMenu(int id) {
        // 获取子菜单
        List<AuthsysMenu> subMenus = this.menuMapper.selectAllByParentId(id);
        if(subMenus != null) {
            for(AuthsysMenu menu:subMenus) {
                // 删除子菜单的meta
                this.metaMapper.deleteByPrimaryKey(menu.getMeta().getId());
                // 删除子菜单
                this.menuMapper.deleteByPrimaryKey(menu.getId());
            }
        }
        // 删除自己的meta
        this.metaMapper.deleteByMnId(id);
        // 删除自己
        this.menuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public AuthsysMenu findParentMenu(Integer id) {
        AuthsysMenu self = this.menuMapper.selectByPrimaryKey(id);
        if(self != null){
            return this.menuMapper.selectByPrimaryKey(self.getParentId());
        }
        return null;
    }

    @Override
    public List<AuthsysMenu> findByRoleId(int rlId) {
        return this.menuMapper.selectByRlId(rlId);
    }
}
